package com.yu.yupicture.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yu.yupicture.Untils.ThrowUntil;
import com.yu.yupicture.common.DeleteRequest;
import com.yu.yupicture.constans.UserConstans;
import com.yu.yupicture.exception.ErrorCode;
import com.yu.yupicture.exception.biusnessException;
import com.yu.yupicture.mapper.UserMapper;
import com.yu.yupicture.model.domain.dto.user.*;
import com.yu.yupicture.model.domain.entry.User;
import com.yu.yupicture.model.domain.vo.UserLoginVo;
import com.yu.yupicture.model.domain.vo.UserVo;
import com.yu.yupicture.model.enums.UserRoleEnums;
import com.yu.yupicture.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Li Shuokang
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2025-07-29 15:33:13
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

//    private final UserService userService;
//
//    public UserServiceImpl(UserService userService) {
//        this.userService = userService;
//    }

    /**
     * 用户注册
     *
     * @param userRegistDto
     * @return
     */
    @Override
    public Long userRegister(userRegistDto userRegistDto) {
        String userPassword = userRegistDto.getUserPassword();
        String checkPassword = userRegistDto.getCheckPassword();
        String userAccount = userRegistDto.getUserAccount();
        //1：校验参数
        if (StrUtil.hasBlank(userAccount, userPassword, checkPassword)) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 5) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "账号长度不能小于5位");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "密码长度不能小于8位");
        }
        if (!userPassword.equals(checkPassword)) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "密码不一致");
        }
        //2：查询数据库是否已经存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserAccount, userAccount);
        User user = this.baseMapper.selectOne(queryWrapper);
        //已经存在，报异常
        if (user != null) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "账号已存在");
        }
        //3：插入数据库
        User newUser = new User();
        newUser.setUserAccount(userAccount);
        newUser.setUserPassword(getEncryptPassword(userPassword));
        newUser.setUserName(UUID.fastUUID().toString(true));
        newUser.setUserRole(UserRoleEnums.USER.getValue());
        this.baseMapper.insert(newUser);
        //4：返回用户id
        return newUser.getId();
    }

    /**
     * 获取加密密码
     */
    @Override
    public String getEncryptPassword(String password) {
        if (StrUtil.isBlank(password)) {
            return null;
        }
        //加盐处理
        String salt = "lsknp";
        return DigestUtils.md5DigestAsHex((password + salt).getBytes());
    }

    /**
     * 对用户信息进行脱敏
     */
    @Override
    public UserLoginVo getSafeUser(User user) {
        if (user == null) {
            return null;
        }
        UserLoginVo userLoginVo = new UserLoginVo();
        BeanUtil.copyProperties(user, userLoginVo);
        return userLoginVo;
    }

    /**
     * 用户登录
     *
     * @param userLoginDto
     * @return
     */
    @Override
    public UserLoginVo userLogin(UserLoginDto userLoginDto, HttpServletRequest request) {
        String userAccount = userLoginDto.getUserAccount();
        String userPassword = userLoginDto.getUserPassword();
        //1：校验参数
        if (StrUtil.hasBlank(userAccount, userPassword)) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 5) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "账号长度不能小于5位");
        }
        if (userPassword.length() < 8) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "密码长度不能小于8位");
        }
        //判断用户是否存在和密码是否正确
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserAccount, userAccount);
        queryWrapper.eq(User::getUserPassword, getEncryptPassword(userPassword));
        User user = this.baseMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "账号或密码错误");
        }
        //设置用户登录状态
        request.getSession().setAttribute(UserConstans.USER_LOGIN_STATE, user);
        //返回用户信息（脱敏）
        return getSafeUser(user);
    }

    /**
     * 获取当前登录用户信息
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        ThrowUntil.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        //1：先判断是否登录
        User attribute = (User) request.getSession().getAttribute(UserConstans.USER_LOGIN_STATE);
        if (attribute == null) {
            throw new biusnessException(ErrorCode.NOT_LOGIN_ERROR, "未登录");
        }
        //2：获取当前登录用户（如果追求性能，可直接返回）
        User user = this.baseMapper.selectById(attribute.getId());
        if (user == null) {
            throw new biusnessException(ErrorCode.SYSTEM_ERROR);
        }
        //3：返回信息
        return user;
    }

    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    @Override
    public boolean logout(HttpServletRequest request) {
        //判断是否登录
        ThrowUntil.throwIf(request.getSession().getAttribute(UserConstans.USER_LOGIN_STATE) == null, ErrorCode.NOT_LOGIN_ERROR);
        //移除登录状态
        request.getSession().removeAttribute(UserConstans.USER_LOGIN_STATE);
        return true;
    }

    /**
     * 创建用户
     *
     * @param userAddRequest
     * @return
     */
    @Override
    public Long addUser(UserAddRequest userAddRequest) {
        String userAvatar = userAddRequest.getUserAvatar();
        String userProfile = userAddRequest.getUserProfile();
        String userRole = userAddRequest.getUserRole();
        String userAccount = userAddRequest.getUserAccount();
        String userName = userAddRequest.getUserName();
        //1.参数校验
        if (StrUtil.hasBlank(userAccount, userName, userRole)) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 5) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "账号长度不能小于5位");
        }

        //2:查询数据库，账号不能重复
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserAccount, userAccount);
        Long l = this.baseMapper.selectCount(queryWrapper);
        if (l > 0) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }

        //3:添加到数据库
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserName(userName);
        user.setUserAvatar(userAvatar);
        user.setUserProfile(userProfile);
        user.setUserRole(userRole);
        user.setUserPassword(getEncryptPassword("123456"));
        this.baseMapper.insert(user);
        return user.getId();
    }

    /**
     * 删除用户
     *
     * @param deleteRequest
     * @return
     */
    @Override
    public boolean deleteUser(DeleteRequest deleteRequest) {
        Long id = deleteRequest.getId();
        //1:校验参数
        ThrowUntil.throwIf(id == null, ErrorCode.PARAMS_ERROR);
        //2：查询用户是否存在
        User user = this.baseMapper.selectById(id);
        if (user == null) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        //3：删除用户
        this.baseMapper.deleteById(id);
        return true;
    }

    /**
     * 获取用户信息
     *
     * @param id
     * @return
     */
    @Override
    public UserVo getUserVo(Long id) {
        //1:校验参数
        ThrowUntil.throwIf(id == null, ErrorCode.PARAMS_ERROR);
        //2:获取用户信息
        User user = this.baseMapper.selectById(id);
        if (user == null) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        //3：封装成VO
        return getUserVo(user);
    }

    /**
     * 用户脱敏
     */
    @Override
    public UserVo getUserVo(User user) {
        if (user == null) {
            return null;
        }
        return BeanUtil.copyProperties(user, UserVo.class);
    }

    /**
     * 获取脱敏用户列表
     *
     * @param list
     * @return
     */
    @Override
    public List<UserVo> getListUserVo(List<User> list) {
        if (CollUtil.isEmpty(list)) {
            return List.of();
        }
        return list.stream().map(this::getUserVo).collect(Collectors.toList());
    }

    /**
     * 根据id获取用户(未脱敏)
     *
     * @param id
     * @return
     */
    @Override
    public User getUser(Long id) {
        //1:校验参数
        ThrowUntil.throwIf(id == null, ErrorCode.PARAMS_ERROR);
        //2:获取用户信息
        User user = this.baseMapper.selectById(id);
        if (user == null) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        //3：封装成VO
        return user;
    }

    /**
     * 修改用户信息（管理员）
     *
     * @param userUpdateRequest
     * @return
     */
    @Override
    public boolean updateUser(UserUpdateRequest userUpdateRequest) {
        //1:校验参数
        ThrowUntil.throwIf(userUpdateRequest == null || userUpdateRequest.getId() == null, ErrorCode.PARAMS_ERROR);

        Long id = userUpdateRequest.getId();
        String userName = userUpdateRequest.getUserName();
        String userAvatar = userUpdateRequest.getUserAvatar();
        String userProfile = userUpdateRequest.getUserProfile();
        String userRole = userUpdateRequest.getUserRole();
        int email = userUpdateRequest.getEmail();
        if (userName != null && userName.length() < 5) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "用户名长度不能小于5位");
        }
        if (userProfile != null && userProfile.length() > 100) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "简介不能超过100位");
        }
        if (email>Integer.MAX_VALUE){
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "微信账号不能超过10位");
        }
        //2:获取用户信息
        User user = this.baseMapper.selectById(userUpdateRequest.getId());
        if (user == null) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }

        User newUser = new User();
        BeanUtil.copyProperties(userUpdateRequest, newUser);
        //3：修改用户信息
        return this.updateById(newUser);
    }

    /**
     * 获取查询包装类
     *
     * @param userQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.like(StrUtil.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    /**
     * 分页查询用户信息（管理端）
     *
     * @param userQueryRequest
     * @return
     */
    @Override
    public Page<UserVo> listUserVoByPage(UserQueryRequest userQueryRequest) {
        int current = userQueryRequest.getCurrent();
        int pageSize = userQueryRequest.getPageSize();
        Page<User> page = this.page(new Page<>(current, pageSize), getQueryWrapper(userQueryRequest));
        Page<UserVo> userVoPage = new Page<>(current, pageSize, page.getTotal());
        userVoPage.setRecords(getListUserVo(page.getRecords()));
        return userVoPage;
    }

}




